/**
 * @author banglong
 * @date 2016/12/22
 */
define(['text!../html/components/common/AccountQuery.html!strip', 'avalon', 'indexApi',
  'tools', 'Layer', 'bus', 'laydate'
], function (htmlTemp, avalon, api, tools, layer, bus) {

  return function () {
    var runtimeParam;
    var getRuntimeParam = function () {
      return {
        timeObj: {},
        monthData: []
      };
    };

    var accountQueryVm;
    var getVmOption = function () {
      return {
        $id: 'accountQuery',
        startTime: '',
        endTime: '',
        year: '',
        yearArr: [],
        month: '',
        // 每个表格组件的id 用于销毁 vm 使用
        tableComponentsID: ['account-info-table', 'bill-detail-table', 'account-year-table', 'account-year-detail-table'],
        // 选项卡
        chooseViewIndex: 0,
        // 改变选项卡
        changeView: function (index) {
          accountQueryVm.chooseViewIndex = index
        },
        accountInfoTable: {
          header: ['账户名称', '期初金额', '进金额', '出金额', '结余金额'],
          row: ['DeptAccountName', 'PreAmount', 'InAmount', 'OutAmount', 'OrginAmount'],
          elementID: 'accountInfoTable',
          data: []
        },
        billDetailTable: {
          header: ['单据类型', '物品代码', '物品名称', '数量', '单价', '进金额', '出金额', '金额', '发生时间', '单据流水号', '批次号'],
          row: ['xxx', 'GoodsCode', 'GoodsName', 'Count', 'Price', 'InAmount', 'OutAmount', 'Balance', 'HappenTime', 'BillSN', 'BatchSN'],
          elementID: 'billDetailTable',
          sourceData: []
        },
        accountYearTable: {
          header: ['账户名称', '年度分配总额', '当前余额', '一月入', '一月出', '二月入', '二月出', '三月入', '三月出', '四月入', '四月出', '五月入', '五月出', '六月入', '六月出', '七月入', '七月出', '八月入', '八月出', '九月入', '九月出', '十月入', '十月出', '十一月入', '十一月出', '十二月入', '十二月出'],
          row: ['DeptAccountName', 'Ndfp', 'Dqye', 'Dyxh1', 'Dyxh1Out', 'Dyxh2', 'Dyxh2Out', 'Dyxh3', 'Dyxh3Out', 'Dyxh4', 'Dyxh4Out', 'Dyxh5', 'Dyxh5Out', 'Dyxh6', 'Dyxh6Out', 'Dyxh7', 'Dyxh7Out', 'Dyxh8', 'Dyxh8Out', 'Dyxh9', 'Dyxh9Out', 'Dyxh10', 'Dyxh10Out', 'Dyxh11', 'Dyxh11Out', 'Dyxh12', 'Dyxh12Out'],
          elementID: 'accountYearTable',
          data: []
        },
        accountYearDetailTable: {
          header: ['月份', '单据类型', '进出标志', '物品代码', '物品名称', '数量', '单价', '金额', '单据流水号', '批次号', '发生时间'],
          row: ['Month', 'BillType', 'IOSign', 'GoodsCode', 'GoodsName', 'IOCount', 'Price', 'Amount', 'BillSN', 'BatchSN', 'HappenTime'],
          elementID: 'accountYearDetailTable',
          sourceData: []
        },
        // 时间段查询
        queryAccountBalanceReport: function () {
          var index = layer.load();
          tools.throttle(runtimeParam.timeObj, function () {
            var n = new Date(accountQueryVm.endTime).getTime() + 24 * 60 * 60 * 1000;
            bus.triggerHandler('accountQuery.queryAccountBalanceReport', {
              startTime: accountQueryVm.startTime,
              endTime: new Date(n).format('yyyy-MM-dd'),
              // deptAccountID: '0000000000s-05',
              deptAccountID: runtimeParam.deptAccountID,
              goodsBookID: runtimeParam.goodsBookID,
              // goodsBookID: '%',
              callback: function (data) {
                layer.close(index);
                accountQueryVm.accountInfoTable.data.splice(0, accountQueryVm.accountInfoTable.data.length);
                accountQueryVm.accountInfoTable.data.push({
                  DeptAccountName: data.DeptAccountName,
                  InAmount: data.InAmount,
                  OrginAmount: data.OrginAmount,
                  OutAmount: data.OutAmount,
                  PreAmount: data.PreAmount
                });
                accountQueryVm.billDetailTable.sourceData.splice(0, accountQueryVm.billDetailTable.sourceData.length);
                accountQueryVm.billDetailTable.sourceData.pushArray(data.Details);
              },
              error: function () {
                layer.close(index);
              }
            })
          });
        },
        // 年度查询
        getAccountInformation: function () {
          var index = layer.load();
          tools.throttle(runtimeParam.timeObj, function () {
            bus.triggerHandler('accountQuery.getAccountInformation', {
              deptAccountID: runtimeParam.deptAccountID,
              year: accountQueryVm.year,
              callback: function (data) {
                layer.close(index);
                accountQueryVm.accountYearTable.data.splice(0, accountQueryVm.accountYearTable.data.length);
                accountQueryVm.accountYearTable.data.pushArray(data.datatable2);
                accountQueryVm.accountYearDetailTable.sourceData.splice(0, accountQueryVm.accountYearDetailTable.sourceData.length);
                runtimeParam.monthData = null;
                runtimeParam.monthData = data.datatable1;
                data = null;
                // 循环 拿去 选中月份的数据
                var monthData = {};
                runtimeParam.monthData.forEach(function (item) {
                  item.IOSign = item.IOSign === 1 ? '入' : '出';
                  // todo
                  switch (item.BillType) {
                    case 'lyzc':
                      item.BillType = '领用单';
                      break;
                  }
                  // 将数据按照月份归类
                  if (!monthData[item.Month]) {
                    monthData[item.Month] = [];
                  }
                  monthData[item.Month].push(item);
                });
                accountQueryVm.accountYearDetailTable.sourceData.pushArray(monthData[accountQueryVm.month]);
                // 将归类好的数据记录起来
                runtimeParam.monthData = monthData;
              },
              error: function () {
                layer.close(index);
              }
            })
          });
        }
      }
    };

    this.init = function (param) {
      runtimeParam = getRuntimeParam();
      runtimeParam = Object.assign({}, runtimeParam, param);

      var vmConfig = getVmOption();
      runtimeParam.layeroObj = tools.createNewOpenWindow(['850px', '620px'], '账户查询', htmlTemp,
        false, {
          vmConfig: vmConfig,
          // 销毁方法
          destroy: function () {
            runtimeParam = null;
            accountQueryVm = null;
          }
        });
      accountQueryVm = tools.initAvalonVm(avalon, vmConfig, '#accountQuery');

      // 初始化日期
      var currentYear = new Date().getFullYear();
      accountQueryVm.startTime = currentYear + '-01-01';
      accountQueryVm.endTime = new Date().format('yyyy-MM-dd');
      accountQueryVm.yearArr = [currentYear - 7, currentYear - 6, currentYear - 5, currentYear - 4, currentYear - 3, currentYear - 2, currentYear - 1];
      accountQueryVm.year = currentYear - 1;
      accountQueryVm.month = '1';
      // 查询初始数据
      accountQueryVm.queryAccountBalanceReport();
      // 初始化时间控件
      setTimeout(function () {
        laydate({
          elem: '#startTime'
        });
        laydate({
          elem: '#endTime'
        });
      }, 300);
      // 监听月份变化
      accountQueryVm.$watch('month', function (month) {
        if (runtimeParam.monthData[month]) {
          accountQueryVm.accountYearDetailTable.sourceData.splice(0, accountQueryVm.accountYearDetailTable.sourceData.length);
          accountQueryVm.accountYearDetailTable.sourceData.pushArray(runtimeParam.monthData[accountQueryVm.month]);
        }
      });
    };
  }
});